<template>
  <div class="cz-login cz-px-2">
    <div class="login_wrapper cz-relative">
      <div class="cz-absolute cz-right-1 cz-top-1">
        <el-button
          icon="Plus"
          link
          type="primary"
          @click="()=> router.push(ROUTER_PREFIX +'/register')"
        >
          新注册
        </el-button>
      </div>
      <div class="cz-login-panel md:cz-w-[480px] cz-w-full">
        <div class="cz-pt-16 cz-flex cz-justify-center">
          <el-avatar
            shape="circle"
            size="large"
            :src="avatar"
          />
          <h3 class="cz-text-center cz-text-3xl cz-px-2 cz-flex cz-items-center">
            十七
          </h3>
        </div>
        <div class="login-form">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="20"
            status-icon
          >
            <el-form-item
              prop="account"
            >
              <el-input
                v-model.trim="ruleForm.account"
                autocomplete="off"
                clearable
                placeholder="请输入登录账号"
                prefix-icon="User"
                size="large"
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            <el-form-item
              prop="password"
            >
              <el-input
                v-model.trim="ruleForm.password"
                autocomplete="off"
                clearable
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password
                size="large"
                type="password"
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            <el-form-item
              v-if="websiteConfig.isCode === YES_OR_NO_ENUM.YES"
              prop="code"
            >
              <el-input
                v-model.number="ruleForm.code"
                clearable
                placeholder="验证码"
                prefix-icon="CircleCheck"
                size="large"
                @keyup.enter="handleLogin"
              >
                <template #append>
                  <img
                    :src="captcha.imageBase"
                    alt="验证码"
                    class="cz-w-[100px] cz-h-10 cz-inline-block cz-cursor-pointer"
                    @click="handleGetCaptcha"
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <div class="cz-flex cz-justify-between cz-w-full">
                <el-checkbox
                  v-model="ruleForm.rememberChecked"
                  label="记住密码"
                />
                <el-button
                  link
                  type="primary"
                >
                  忘记密码？
                </el-button>
              </div>
            </el-form-item>
            <div class="cz-flex cz-justify-between cz-items-center login_button">
              <el-button
                icon="RefreshLeft"
                size="large"
                @click="handleResetForm"
              >
                重置
              </el-button>
              <el-button
                icon="Position"
                size="large"
                type="primary"
                @click="handleLogin"
              >
                {{ loginLoading ? '正在登录' : '立即登录' }}
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
  <div class="wallpaper">
    <video
      ref="videoRef"
      muted
      autoplay
      loop
    >
      <source
        src="../assets/video.mp4"
        type="video/mp4"
      >
    </video>
  </div>
</template>

<script lang="ts" setup>
import { useCloneDeep, useEmptyObject, useOmit } from 'co-utils-vue';
import { ElMessage, FormInstance } from 'element-plus';
import { ref } from 'vue';
import { RouteLocationRaw } from 'vue-router';

import { getSystemCaptcha } from '@/api/system';
import { ISystemCaptcha, IWebsite } from '@/api/system/type';
import { User } from '@/api/user/type';
import avatar from '@/assets/default-avatar.jpg';
import { ROUTER_PREFIX, YES_OR_NO_ENUM } from '@/constant';
import { useSystemStore, useUserStore } from '@/hooks/store';
import { useSM4DeCrypto, useSM4EnCrypto } from '@/hooks/use-crypt';
import { useGetAccountCookie, useRemoveAccountCookie, useSetAccountCookie } from '@/hooks/use-utils/auth';

const userStore = useUserStore();
const systemStore = useSystemStore();
defineOptions({
  name: 'Login'
});
const ruleFormRef = ref<FormInstance>();
const loginLoading = ref(false);
const websiteConfig = ref({} as IWebsite.Data);
const captcha = ref({} as ISystemCaptcha.Data);
const route = useRoute();
interface IForm extends User.ILoginRequest {
  rememberChecked: boolean;
}

const ruleForm = ref<IForm>({
  account: '',
  password: '',
  code: '',
  codeKey: 0,
  rememberChecked: false

});
const router = useRouter();
const validatePassword = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  }
  callback();
};

const validateUsername = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'));
  }
  callback();
};
const checkCode = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'));
  }
  callback();
};
const rules = ref({
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  account: [{ required: true, validator: validateUsername, trigger: 'blur' }],
  code: [{ required: true, validator: checkCode, trigger: 'blur' }]
});
const handleRememberPassword = (v: boolean) => {
  if (v) {
    const _form = useCloneDeep(ruleForm.value);
    _form.password = useSM4EnCrypto(_form.password);
    useSetAccountCookie(JSON.stringify(useOmit(_form, ['code', 'codeKey'])));
    return;
  }
  const account = useGetAccountCookie();
  if (account) useRemoveAccountCookie();
};
const handleGetCaptcha = async () => {
  captcha.value = await getSystemCaptcha();
};
const handleResetForm = () => {
  ruleFormRef.value?.resetFields();
};
const handleLogin = async () => {
  try {
    await ruleFormRef.value!.validate();
    loginLoading.value = true;
    await userStore.login(useOmit(ruleForm.value, ['rememberChecked']));
    handleRememberPassword(ruleForm.value.rememberChecked);
    loginLoading.value = false;
    ElMessage.success('登录成功');
    const { redirect = '/' } = route.query;
    console.log(redirect);
    await router.replace(redirect as RouteLocationRaw);
  } catch (e) {
    loginLoading.value = false;
    await handleGetCaptcha();
  }
};
const handleGetUserAccount = () => {
  const account = useGetAccountCookie();
  if (account) {
    const _account = JSON.parse(account);
    console.log(useSM4DeCrypto(_account.password));
    ruleForm.value = { ..._account, password: useSM4DeCrypto(_account.password) };
    return;
  }
  ruleForm.value = useEmptyObject(ruleForm.value);
};
const handleWebsiteConfig = async () => {
  websiteConfig.value = await systemStore.getWebsite();
  if (websiteConfig.value.isCode === YES_OR_NO_ENUM.YES) {
    await handleGetCaptcha();
  }
};
onMounted(() => {
  handleGetUserAccount();
  handleWebsiteConfig();
});
</script>

<style lang="scss" scoped>
.wallpaper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; /* 确保视频在其他内容之后显示 */
}

video {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
.cz-login {
  //background: url("https://www.bing.com/th?id=OHR.AssiniboineProvincialPark_ZH-CN2270275151_1920x1080.jpg") no-repeat;
  width: 100%;
  height: 100vh;
  background-size: cover;
  display: flex;
  align-items: center;
  position: relative;
  justify-content: center;

  .login_wrapper {
    .cz-login-panel {
      background: rgba(var(--bs-body-bg-rgb), .9);
      border-radius: 12px;

      .login-form {
        padding: 30px 40px 10px 40px;

        .login_button {
          border-radius: 25px;
          height: 50px;
          width: calc(100% - 25px);
          margin: 20px 0 20px 20px;
        }
      }
    }
  }
}

:deep(.login-form .el-input-group__append) {
  padding: 0;
  overflow: hidden;
}
</style>
